import java.util.*;

public class FindSubstring {
    /**
     * 因为题目说了words数组中的字符串的长度是一样的所以我们的指针可以一次移动一个单词的位置，
     * 并且从[0,单词长度]开始遍历就可以得到所有的情况
     * @param s
     * @param words
     * @return
     */
    public List<Integer> findSubstring(String s, String[] words) {
        Map<String, Integer> hash1 = new HashMap<>();
        for (String word : words) hash1.put(word,hash1.getOrDefault(word,0) + 1);
        int len1 = words.length, len2 = words[0].length();
        List<Integer> ret = new ArrayList<>();
        for (int i = 0; i < len2; i++) {
            Map<String, Integer> hash2 = new HashMap<>();
            for (int left = i, right = i, count = 0; right + len2 <= s.length()
                    ; right += len2) {
                //进窗口
                String in = s.substring(right,right + len2);
                hash2.put(in,hash2.getOrDefault(in,0) + 1);
                if (hash2.get(in) <= hash1.getOrDefault(in,0)) count++;
                //判断
                if (right - left + 1 > len1 * len2) {
                    String out = s.substring(left,left + len2);
                    if (hash2.get(out) <= hash1.getOrDefault(out,0)) count--;
                    hash2.put(out,hash2.get(out) - 1);
                    left += len2;
                }
                if (count == len1) ret.add(left);
            }
        }
        return ret;
    }
}
